package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserAuthControllerImpl implements UserAuthService {
    private final UserClient userClient;
    private final JwtUtils jwtUtils;

    public UserAuthControllerImpl(UserClient userClient, JwtUtils jwtUtils) {
        this.userClient = userClient;
        this.jwtUtils = jwtUtils;
    }


    /*
     * 1.对密码和用户名进行验证
     * 2.首先是判断用户名是否为null，如果是则抛出异常
     * 3.如果正确，生成jwt凭证，查询错误则返回400
     * 3.1准备用户信息将生成jwt的信息写入到cookie中。
     * */
    @Override
    public void login(String username, String password, HttpServletResponse httpServletResponse) {

        try {
           // UserDTO user = userClient.queryByUsernameAndPassword(username, password);
            UserDTO user = userClient.queryUserByNameAndPass(username,password);
            if (user == null) {
                throw new LyException(400, "用户名或密码错误");
            }

            UserDetail userDetail = UserDetail.of(user.getId(), user.getUsername());
            String jwt = jwtUtils.createJwt(userDetail);
            writeCookie(httpServletResponse, jwt);  //调用下面的方法writeCookie
        } catch (FeignException e) {
            throw new LyException(e.status(), e.contentUTF8());  //捕获异常
        }
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取cookie信息然后从redis删除

        try {
            String token = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
            Payload payload = jwtUtils.parseJwt(token);
            String username = payload.getUserDetail().getUsername();

            String key = JwtConstants.KEY_PREFIX + username;

            redisTemplate.delete(key);
        } catch (Exception e) {
        }


        //创建cookie，名称固定，值为token
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, "");

        //设置cookie绑定的域名
        cookie.setDomain(JwtConstants.DOMAIN);

        //立即删除
        cookie.setMaxAge(0);

        //绑定给当前域名下的路径
        cookie.setPath("/");

        //拒绝脚本操作和访问
        cookie.setHttpOnly(true);

        response.addCookie(cookie);
    }

    private void writeCookie(HttpServletResponse httpServletResponse, String token) {

        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, token);
        cookie.setDomain(JwtConstants.DOMAIN);  //作用域
        cookie.setHttpOnly(true);               // 是否禁止JS操作cookie，避免XSS攻击
        cookie.setMaxAge(-1);                   // cookie有效期，-1就是跟随当前会话，浏览器关闭就消失
        cookie.setPath("/");                    // cookie作用的路径，/代表一切路径
        httpServletResponse.addCookie(cookie);
    }
}
